var api = require('./api.js');

const formatTime = (date) => {
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();
    const hour = date.getHours();
    const minute = date.getMinutes();
    const second = date.getSeconds();
    return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`;
};
// const localIP = 'https://shareparking.wasu.cn/icommunity-web'; //正式环境域名
// const localIP = "https://shareparking.wasu.cn/test/icommunity-web"; //测试环境域名
const formatNumber = (n) => {
    n = n.toString();
    return n[1] ? n : `0${n}`;
}; //封装微信/wx-app的request

function request(url, data = {}, method = 'GET', contentType) {
    return new Promise(function (resolve, reject) {
        // console.log('请求连接：' + url);
        uni.request({
            url:url,
            data: data,
            method: method,
            header: {
                'Content-Type': contentType || 'application/json',
                Authorization: uni.getStorageSync('AUTHORIZATION'),
                appCode: 'GAT-LIFE'
            },
            // 4d64cae7-2895-468f-bd0f-b7dad2e36a6b
            success: (res) => {
                if (res.statusCode == 200) {
                    //需要跟后端确定这些错误码以及登录状态
                    if (res.data.errno == 401) {
                        //登录后才可以操作
                        let code = null;
                        return login()
                            .then((res) => {
                                code = res.code;
                                return getUserInfo();
                            })
                            .then((userInfo) => {
                                request(
                                    api.login,
                                    {
                                        code: code,
                                        userInfo: userInfo
                                    },
                                    'POST'
                                )
                                    .then((res) => {
                                        if (res.errno == 0) {
                                            //存储用户信息
                                            uni.setStorageSync('userInfo', res.data.userInfo);
                                            uni.setStorageSync('token', res.data.token);
                                            resolve(res);
                                        } else {
                                            reject(res);
                                        }
                                    })
                                    .catch((err) => {
                                        reject(err);
                                    });
                            })
                            .catch((err) => {
                                reject(err);
                            });
                    } else {
                        resolve(res.data);
                    }
                } else if (res.statusCode == 911) {
                    if (uni.getStorageSync('userType') == 'guest') {
                        console.log('游客访问中');
                    } else {
                        uni.showToast({
                            title: '登录已过期，正在跳转登录，请稍后...',
                            icon: 'none'
                        });
                        setTimeout(() => {
                            var activityCode, shareId;

                            if (uni.getStorageSync('activityCode')) {
                                activityCode = uni.getStorageSync('activityCode') || '';
                            }

                            if (uni.getStorageSync('shareId')) {
                                shareId = uni.getStorageSync('shareId') || '';
                            }

                            // uni.clearStorageSync();

                            if (activityCode) {
                                uni.setStorageSync('activityCode', activityCode);
                            }

                            if (shareId) {
                                uni.setStorageSync('shareId', shareId);
                            }
							// alert(uni.getStorageSync('weixin'))
							if (uni.getStorageSync('weixin') == 2) {
								jWeixin.miniProgram.reLaunch({
									url: "/pages/login/login"
								})
							} else {
								if(uni.getStorageSync('weixin') == 3 || uni.getStorageSync('weixin') == 4){
									uni.reLaunch({
										url: '/pages/indexk/indexk'
									})	
								}else{
									uni.reLaunch({
										url: '/pages/login/index'
									});	
								}

							}

                        }, 2000);
                    }
                } else {
                    reject(res.errMsg);
                }
            },
            fail: function (err) {
                // console.log('请求连接：' + url + '报错');
                // console.log('报错原因：' + JSON.stringify(err));
                reject(err);
            }
        });
    });
}

function get(url, data = {}) {
    return request(url, data, 'GET');
}

function post(url, data = {}) {
    return request(url, data, 'POST');
}

function compareVersion(v1, v2) {
    v1 = v1.split('.');
    v2 = v2.split('.');
    const len = Math.max(v1.length, v2.length);

    while (v1.length < len) {
        v1.push('0');
    }

    while (v2.length < len) {
        v2.push('0');
    }

    for (let i = 0; i < len; i++) {
        const num1 = parseInt(v1[i]);
        const num2 = parseInt(v2[i]);

        if (num1 > num2) {
            return 1;
        } else if (num1 < num2) {
            return -1;
        }
    }

    return 0;
}
/**
 * 修改时间戳转换为年月日时分秒
 *   fmt  例如：yyyy-MM-dd hh:mm:ss ||  yyyy-MM-dd  || yyyy.MM  等等，可随意搭配年月日时分秒
 */

function getDate(val, fmt) {
    if (!val) {
        return '';
    }

    if (val && val.length == 10) {
        val = parseInt(val * 1000);
    }

    var date = new Date(val);
    var o = {
        'M+': date.getMonth() + 1,
        //月份
        'd+': date.getDate(),
        //日
        'h+': date.getHours(),
        //小时
        'm+': date.getMinutes(),
        //分
        's+': date.getSeconds(),
        //秒
        'q+': Math.floor((date.getMonth() + 3) / 3),
        //季度
        S: date.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));

    for (var k in o) if (new RegExp('(' + k + ')').test(fmt)) fmt = fmt.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length));

    return fmt;
}
/**
 * yyyy-mm-dd hh:mm:ss转换为时间戳
 */

function zhuanhuan(stringTime) {
    var timestamp2 = stringTime.replace(/-/g, '/'); //为了兼容IOS，需先将字符串转换为'2018/9/11 9:11:23'

    timestamp2 = Date.parse(timestamp2); //返回的时间戳

    return timestamp2;
}
/*
 ** randomWord 产生任意长度随机字母数字组合
 ** randomFlag-是否任意长度 min-任意长度最小位[固定位数] max-任意长度最大位
 */
// function randomWord(min){
//   var str = ""
//   var range = min
//    var arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
//   for(var i=0; i<range; i++){
//     pos = Math.round(Math.random() * (arr.length-1));
//     str += arr[pos];
//   }
//   return str;
// }
//   // js创建含数字字母的随机字符串

function randomWord() {
    var text = '';
    var possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';

    for (var i = 0; i < 10; i++) text += possible.charAt(Math.floor(Math.random() * possible.length));

    return text;
} // 手机号脱敏

function noPassByMobile(str) {
    if (null != str && str != undefined) {
        var pat = /(\d{3})\d*(\d{4})/;
        return str.replace(pat, '$1****$2');
    } else {
        return '';
    }
}

module.exports = {
    formatTime,
    request,
    get,
    post,
    compareVersion,
    getDate,
    zhuanhuan,
    randomWord,
    noPassByMobile
};
